package org.xtense.rcp.preferences;

import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;

import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.xtense.data.DBConfig;
import org.xtense.data.DBManager;
import org.xtense.rcp.Activator;
import org.xtense.util.StringUtil;

public class DatabasePage extends PreferencePage implements
		IWorkbenchPreferencePage, ModifyListener, Listener {
	private static final String CLASSNAME_DEFAULT = "com.mysql.jdbc.Driver";
	private static final String URL_DEFAULT = "jdbc:mysql://localhost:3306/xmldb";
	private static final String USERNAME_DEFAULT = "root";
	private static final String PASSWORD_DEFAULT = "root";

	private Text classNameText, urlText, userNameText, passwordText;
	private Button validateConnection;

	private IPreferenceStore ps;

	@Override
	protected Control createContents(Composite parent) {
		ps = getPreferenceStore();
		Composite topComp = new Composite(parent, SWT.NONE);
		topComp.setLayout(new GridLayout());
		createConnectGroup(topComp);

		validateConnection = new Button(topComp, SWT.NONE);
		{
			validateConnection.setAlignment(SWT.RIGHT);
			GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
			validateConnection.setLayoutData(gridData);
			validateConnection.setText("Validate the Configuration");
			validateConnection.addListener(SWT.Selection, this);
		}
		return topComp;
	}

	private void createConnectGroup(Composite topComp) {
		Group group = new Group(topComp, SWT.NONE);
		group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		group.setLayout(new GridLayout(2, false));
		group.setText("Database Connection");
		classNameText = createText(group, "ClassName:",
				PreferencesConstants.CLASSNAME_KEY, CLASSNAME_DEFAULT, true);
		urlText = createText(group, "URL:", PreferencesConstants.URL_KEY,
				URL_DEFAULT, true);
		userNameText = createText(group, "User Name:",
				PreferencesConstants.USERNAME_KEY, USERNAME_DEFAULT, true);
		passwordText = createText(group, "Password:",
				PreferencesConstants.PASSWORD_KEY, PASSWORD_DEFAULT, false);
		passwordText.setEchoChar('*');
	}

	private Text createText(Composite comp, String label, String saveKey,
			String defaultValue, boolean validateEmpty) {
		new Label(comp, SWT.NONE).setText(label);
		Text text = new Text(comp, SWT.BORDER);
		text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		String value = ps.getString(saveKey);
		if (validateEmpty) {
			text.setText(StringUtil.isEmpty(value) ? defaultValue : value);
		} else {
			text.setText(value);
		}

		text.addModifyListener(this);
		return text;
	}

	@Override
	public void init(IWorkbench workbench) {
		setPreferenceStore(Activator.getDefault().getPreferenceStore());
	}

	@Override
	public void modifyText(ModifyEvent e) {
		String errorStr = null;
		if (StringUtil.isEmpty(classNameText.getText())) {
			errorStr = "ClassName Field can't be empty.";
		} else if (StringUtil.isEmpty(urlText.getText())) {
			errorStr = "URL Field can't be empty.";
		} else if (StringUtil.isEmpty(userNameText.getText())) {
			errorStr = "UserName Field can't be empty";
		}
		setErrorMessage(errorStr);
		setValid(errorStr == null);
		getApplyButton().setEnabled(errorStr == null);
	}

	private void doSave() {
		ps
				.setValue(PreferencesConstants.CLASSNAME_KEY, classNameText
						.getText());
		ps.setValue(PreferencesConstants.URL_KEY, urlText.getText());
		ps.setValue(PreferencesConstants.USERNAME_KEY, userNameText.getText());
		ps.setValue(PreferencesConstants.PASSWORD_KEY, passwordText.getText());
	}

	public boolean performOk() {
		doSave();
		return true;
	}

	protected void performDefaults() {
		classNameText.setText(CLASSNAME_DEFAULT);
		urlText.setText(URL_DEFAULT);
		userNameText.setText(USERNAME_DEFAULT);
		passwordText.setText(PASSWORD_DEFAULT);
		updateApplyButton();
	}

	@Override
	public void handleEvent(Event event) {
		if (event.type == SWT.Selection) {
			if (event.widget == validateConnection) {
				DBManager manager = new DBManager(DBConfig.getInstance(false,
						new String[] { classNameText.getText(),
								urlText.getText(), userNameText.getText(),
								passwordText.getText() }));
				String message;
				if (manager.validateConnection()) {
					message = "Connected to the database successfully.";
				} else {
					message = "Fail to initialize a connection.";
				}
				setMessage(message);
			}
		}

	}

}
